<?php

namespace app\common\model\xiluedu;

use app\common\model\User;
use think\Db;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;
use function fast\array_get;


class CourseComment extends Model
{
    use SoftDelete;
    // 表名
    protected $name = 'xiluedu_course_comment';

    protected $autoWriteTimestamp = 'int';

    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    protected $append = [
        'createtime_text'
    ];

    public function user() {
        return $this->belongsTo(User::class, 'user_id')->setEagerlyType(0);
    }

    public function course() {
        return $this->belongsTo('Course', 'course_id')->setEagerlyType(0);
    }

    public function getCreatetimeTextAttr($value,$data){
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i", $value) : $value;
    }

    public static function init() {
        $updateCompanyScore = function($row) {
            $course_id = $row->course_id;
            $ret = Db::name('xiluedu_course_comment')
                ->where('course_id',$course_id)
                ->whereNUll('deletetime')
                ->fieldRaw('sum(score) as total, count(*) times')
                ->find();
            if($ret && $ret['times']>0) {
                $score = intval($ret['total'] / $ret['times']);
            }else {
                $score = 0;
            }
            Db::name('xiluedu_course')->where('id',$course_id)->update(['avg_score'=>$score,'comment_count'=>$ret['times'] ?? 0]);
        };
        self::afterInsert($updateCompanyScore);
        self::afterDelete($updateCompanyScore);
    }

    /**
     * 课程评价
     * @param $params
     * @return CourseComment|\Exception
     * @throws Exception
     */
    public static function addComment($params) {
//        $hasComment = self::where('user_id',$params['user_id'])
//            ->where('course_id', $params['course_id'])
//            ->count()>0;
//        if($hasComment) {
//            throw new Exception('您已经发布过评论');
//        }
        try {
            $comment = new self();
            $params['content'] = array_get($params,'content', '');
            $params['status'] = 1;
            $ret = $comment->save($params);
            if ($ret === false) {
                throw new Exception($comment->getError());
            }
            return $comment;
        }catch (\Exception $e) {
            throw $e;
        }

    }

    /**
     * 评价列表
     */
    public static function lists($course_id,$pagesize=10){
        return self::where('course_comment.course_id',$course_id)
            ->with([
                'user'=>function($query){$query->withField('id,avatar,nickname');}
            ])
            ->where('course_comment.status','2')
            ->order('id','desc')
            ->paginate($pagesize);
    }

}
